﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace IotS.Core.Repositories.Impl
{
    public class BaseRepository<TKey, T> : IBaseRepository<TKey, T> where T : class
    {
        private readonly IotSDbContext _context;
        private readonly DbSet<T> _set;

        public BaseRepository(IotSDbContext context)
        {
            _context = context;
            _set = _context.Set<T>();
        }

        public async Task<T> InsertAsync(T entity, CancellationToken cancellationToken = default(CancellationToken))
        {
            var model = await _set.AddAsync(entity, cancellationToken);
            return model.Entity;
        }

        public T UpdateAsync(TKey id, T entity)
        {
            var model = _set.Update(entity);
            return model.Entity;
        }

        public void Remove(TKey id)
        {
            var entity = _set.Find(id);
            _set.Remove(entity);
        }

        public void Remove(T entity)
        {
            _set.Remove(entity);
        }

        public Task<T> Get(TKey id)
        {
            return _set.FindAsync(id);
        }

        public IQueryable<T> Query()
        {
            return _set;
        }

        public void Dispose()
        {
            _context?.SaveChanges();
            _context?.Dispose();
        }
    }

    public class BaseRepository<T> : BaseRepository<int, T>, IBaseRepository<T> where T : class
    {
        public BaseRepository(IotSDbContext context) : base(context)
        {
        }
    }
}
